import os
import re

import execjs
import requests


def split_samples(sample, per_subsection):
    num_subsections = len(sample) // per_subsection
    remainder = len(sample) % per_subsection
    subsection_sizes = [per_subsection] * num_subsections
    if remainder > 0:
        subsection_sizes.append(remainder)
        num_subsections += 1
    return num_subsections, subsection_sizes


def split_process(subsection, process_count):
    subsection_per_process = len(subsection) // process_count
    remainder = len(subsection) % process_count
    lengths = []
    start = 0
    for i in range(process_count):
        end = start + subsection_per_process + (1 if i < remainder else 0)
        lengths.append(end - start)
        start = end
    return lengths


def is_http_request(header_text):
    return any(header_text.startswith(method) for method in
               ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'])


def is_http_response(header_text):
    return header_text.startswith("HTTP/")


def fill_missing_keys(dict_list):
    all_keys = set()
    for d in dict_list:
        all_keys.update(d.keys())
    default_dict = {key: '' for key in all_keys}

    def generate_filled_dicts(dicts, default_dict):
        for d in dicts:
            filled_dict = default_dict.copy()
            filled_dict.update(d)
            yield filled_dict

    result = list(generate_filled_dicts(dict_list, default_dict))
    return result


def firstOrZero(param):
    if type(param).__name__ == 'list':
        if (len(param)) != 0:
            return param[0]
        else:
            return 0
    else:
        return 0


def get_uri_depth(url):
    # 匹配从开头到 ? 之间的部分
    match = re.match(r'^[^?]*', url)
    if match:
        path = match.group(0)

        # 去除协议和域名部分
        path = re.sub(r'^https?://[^/]+', '', path)
        segments = [segment for segment in path.split('/') if segment]

        return len(segments)
    return 0


def get_uri_filename_length(uri):
    match = re.search(r'\.([^./?#]+)$', uri)
    if match:
        extension = match.group(0)
        return len(extension)
    return 0


def get_project_root(root_marker="catch_es"):
    current_directory = os.getcwd()
    while current_directory != os.path.dirname(current_directory):
        if os.path.basename(current_directory) == root_marker:
            return f"{current_directory}{os.sep}"
        current_directory = os.path.dirname(current_directory)
    print(f"未找到项目根目录: {root_marker}")
    exit(0)


def parse_expression(expression):
    if expression:
        with open(f"{get_project_root()}base/arkimeparse.js", "r") as f:
            ctx = execjs.compile(f.read())
        return ctx.call("parse_exp", expression)
    else:
        return None


def build_expression(size, start_time, end_time, arkime_expression):
    expression = {"query": {"bool": {"filter": []}}}
    if size:
        expression['size'] = size
    if start_time:
        expression['query']['bool']['filter'].append({"range": {"firstPacket": {"gte": round(start_time.timestamp() * 1000)}}})
    if end_time:
        expression['query']['bool']['filter'].append({"range": {"lastPacket": {"lte": round(end_time.timestamp() * 1000)}}})
    arkime_2_es=parse_expression(arkime_expression)
    if arkime_2_es:
        expression['query']['bool']['filter'].append(arkime_2_es)
    return expression

def send_notice(content):
    requests.post("https://gitee.com/api/v5/notifications/messages", data={
        "access_token": "274e51d37bdb56d47e9f1718836ebd19",
        "username": "jimonik",
        "content": content,
    })